import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:flutter/material.dart' hide Action;
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'item/action.dart';
import 'item/state.dart';
import 'state.dart';

Effect<StudentListState> buildEffect() {
  return combineEffects(<Object, Effect<StudentListState>>{
    Lifecycle.initState: _onReload,
    StudentListAction.onLoad: _onLoad,
    StudentListAction.onReload: _onReload,
    StudentListAction.onAdd: _onAdd,
    StudentListAction.onDelete: _onDelete,
  });
}

void _onReload(Action action, Context<StudentListState> ctx) async {
  if (ctx.state.isLoading) {
    return;
  }

  if (action.payload != null) {
    action.payload(); // callback
  }

  _getStudent(action, ctx, GlobalState.firstPageIndex, GlobalState.pageSize);
}

void _onLoad(Action action, Context<StudentListState> ctx) async {
  var pageIndex = ctx.state.pageIndex;
  var total = ctx.state.pageTotal;
  var isLoading = ctx.state.isLoading;
  if (pageIndex >= total || isLoading) {
    return;
  }

  _getStudent(action, ctx, pageIndex, GlobalState.pageSize);
}

void _onDelete(Action action, Context<StudentListState> ctx) async {
  bool ok = await Util.showConfirmDialog('删除', '确定要删除？', ctx.context);
  if (!ok) {
    return;
  }

  var code = action.payload;

  ctx.dispatch(StudentActionCreator.loading());
  var result = await Http.post(
      GlobalState.isTeacher
          ? '/correct/teacher/api/class/del.mvc'
          : '/correct/student/api/class/exit.mvc',
      data: {'code': code});
  ctx.dispatch(StudentActionCreator.loaded());

  if (result.success) {
    ctx.dispatch(StudentListActionCreator.deleted(code));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _onAdd(Action action, Context<StudentListState> ctx) async {
  Map<String, String> data = {};
  if (GlobalState.isTeacher) {
    data = await _inputStudentInfo(ctx);
  } else {
    String code = await Util.showInputDialog(
        '加入班级', '输入班级码加入班级，与小伙伴一起进步', '请输入班级码', '', ctx.context);
    if (code != null) {
      data = {'code': code};
    }
  }

  if (!(data?.isNotEmpty == true)) {
    return;
  }

  ctx.dispatch(StudentListActionCreator.loading());
  var result = await Http.post(
      '/correct/${GlobalState.userRole}/api/class/add.mvc',
      data: data);
  ctx.dispatch(StudentListActionCreator.loaded());

  if (result.success) {
    ctx.dispatch(StudentListActionCreator.onReload(null));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _getStudent(Action action, Context<StudentListState> ctx, int pageIndex,
    int pageSize) async {
  ctx.dispatch(StudentListActionCreator.loading());

  var result = await Http.get('/correct/teacher/api/student/list.mvc',
      query: {'code': ctx.state.klass.id});

  ctx.dispatch(StudentListActionCreator.loaded());
  if (result.success) {
    var responseList = result.data;
    var pageTotal = 0;

    pageIndex += 1;
    List<StudentState> items = new List();
    if (responseList != null) {
      responseList.forEach((item) {
        try {
          StudentState cellData = new StudentState.fromJson(item);
          items.add(cellData);
        } catch (e) {
          // No specified type, handles all
        }
      });
    }

    ctx.dispatch(
        StudentListActionCreator.listResult(items, pageTotal, pageIndex));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

List<DropdownMenuItem> _gradeItemList() {
  final List<DropdownMenuItem> items = List();
  GlobalState.grades.forEach((key, value) {
    items.add(DropdownMenuItem(value: key, child: Text(value)));
  });
  return items;
}

Future<Map<String, String>> _inputStudentInfo(
    Context<StudentListState> ctx) async {
  String name = '';
  String grade = 'grade3';

  bool ok = await Alert(
      context: ctx.context,
      title: "创建班级",
      content: StatefulBuilder(builder: (context, StateSetter setState) {
        return Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                labelText: '请填写班级名称',
              ),
              onChanged: (input) => name = input,
            ),
            DropdownButton(
              isExpanded: true,
              hint: Text('请选择年级'),
              value: grade,
              items: _gradeItemList(),
              onChanged: (item) {
                setState(() {
                  grade = item;
                });
              },
            ),
          ],
        );
      }),
      buttons: [
        DialogButton(
          onPressed: () => Navigator.pop(ctx.context, false),
          child: Text(
            "取消",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
        DialogButton(
          color: Colors.blue,
          onPressed: () => Navigator.pop(ctx.context, true),
          child: Text(
            "修改",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        )
      ]).show();

  if (ok == true) {
    if (name.isEmpty) {
      Util.alert('班级名称不能为空', ctx.context);
      return null;
    }

    return {'name': name, 'gradeId': grade, 'memo': ''};
  }

  return null;
}
